#pragma once
#include "Comm.hpp"

class Init
{
    public:
    Init()
    {
        umask(0);
        int n = ::mkfifo(gpipeFile.c_str(),gmode);

        if(n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
        }
        std::cout << "mkfifo make success" << std::endl;   
    }
    ~Init()
    {
        int n = ::unlink(gpipeFile.c_str());
        if(n < 0)
        {
            std::cerr << "unlink error" << std::endl;
        }
        std::cout << "unlink make success" << std::endl;  
    }
};

Init init;

class Server
{
public:
    Server()
    :_fd(gdefultfd)
    {}

    bool OpenPipe()
    {
        // 如果读端打开文件时，写端还没打开，读端对应的open就会阻塞。
        _fd = open(gpipeFile.c_str(),O_RDONLY);
        if(_fd < 0)
        {
            std::cerr << "open error" << std::endl;
            return false;
        }
        return true;
    }

    // string *:输出型参数
    // const string &:输入型参数
    // string &:输入输出型参数
    int RecvPipe(std::string *out)
    {
        char buffer[gsize];
        ssize_t n = ::read(_fd, buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    void ClosePipe()
    {
        if(_fd >= 0)
            ::close(_fd);
    }

    ~Server()
    {}
private:
    int _fd;
};